package com.studytime;

import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ShowToast")
public class MeasureActivity extends Activity implements SensorEventListener,LocationListener {

	private Button measureButton;
	private ImageButton studyButton;
	private int temp;
	private double lux = 0;
	private double rate;
	private double tempRate = 0;
	private double luxRate = 0;
	private RatingBar ratingBar;
	private String txtResult;
	private TextView textResult;
	private String tempTxt;
	private String luxTxt;
	private double lat, lon;

	private SensorManager sensorManager = null;
	private Sensor currentSensor = null;

	protected LocationManager locationManager;
	protected LocationListener locationListener;

	public void onCreate(Bundle savedInstanceState) {
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy); 
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_measure);

		//Get GPS location is prepared for measure button click
		getLocation();

		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		textResult = (TextView) findViewById(R.id.textResult);

		measureButton = (Button) findViewById(R.id.measureBtn);
		measureButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				//getLocation();
				myAsyncTask myWebFetch = new myAsyncTask();
		        myWebFetch.execute();
				Toast.makeText(MeasureActivity.this,"lat=" + lat + ", lon=" + lon, Toast.LENGTH_SHORT).show();
				System.out.println("lat=" + lat + ", lon=" + lon);
				getRate();
			}
		});

		studyButton = (ImageButton) findViewById(R.id.studyBtn);
		studyButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent(MeasureActivity.this,
						StudyActivity.class);
				startActivity(intent);
			}
		});
		//Set app to use light sensor
		sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
		currentSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
		if (currentSensor != null) {
			sensorManager.registerListener(this, currentSensor,
					SensorManager.SENSOR_DELAY_FASTEST);
		} else {
			((TextView) findViewById(R.id.textView1))
					.setText("Can't initialize the LIGHT sensor.");
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}

	@Override
	//Get sensor value
	public void onSensorChanged(SensorEvent event) {
		String l;
		if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
			l = String.format("%.02f", event.values[0]);
			lux = Double.parseDouble(l);
		}
	}
	
	//Get location from GPS
	public void getLocation() {
		 locationManager = (LocationManager)
		 getSystemService(Context.LOCATION_SERVICE);
		 if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
			 Toast.makeText(MeasureActivity.this,"GPS is off, Please turn GPS on", Toast.LENGTH_SHORT).show();
		    }
		 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
		 0, 0, (LocationListener) this);
	}
	@Override
	public void onLocationChanged(Location location) {
		lat = location.getLatitude();
		lon = location.getLongitude();
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
//		Toast.makeText(MeasureActivity.this,"Please turn GPS on", Toast.LENGTH_SHORT);
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	class myAsyncTask extends AsyncTask<Void, Void, Void>{
		NodeList nodes;
		URL url;
		URLConnection conn;
		Document doc,doc1;
		DocumentBuilderFactory factory;
		DocumentBuilder builder;
		String woeid = "";
		
		myAsyncTask(){
    		try{
    			//Connect to yahoo service. This will get woeid-instant from GPS latitude and longtitude 
    			url = new URL("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text='"+lat+","+lon+"'%20and%20gflags='R'");
                conn = url.openConnection();                
                factory = DocumentBuilderFactory.newInstance();
                builder = factory.newDocumentBuilder();
                doc = builder.parse(conn.getInputStream());
                nodes = doc.getElementsByTagName("woeid");
                Element element = (Element) nodes.item(0);
                woeid = getCharacterDataFromElement(element);
    			
              //Connect to yahoo service. This will get temperature from woeid 
    			url = new URL("http://weather.yahooapis.com/forecastrss?w="+woeid+"&u=c");
                conn = url.openConnection();
                factory = DocumentBuilderFactory.newInstance();
                builder = factory.newDocumentBuilder();
                doc = builder.parse(conn.getInputStream());                
                nodes = doc.getElementsByTagName("yweather:condition");                
                // Parsing XML
                element = (Element) nodes.item(0);
                temp = Integer.parseInt(element.getAttribute("temp"));
    		}
            catch (Exception e) {
            	System.out.println("error");
            	System.out.println("XML Pasing Excpetion = " + e);
            }
		}
		@Override
		protected Void doInBackground(Void... params) {
			System.out.println("background");
            return null;
		}
		public String getCharacterDataFromElement(Element e)
		{
		    Node child = e.getFirstChild();
		    if (child instanceof CharacterData)
		    {
		        CharacterData cd = (CharacterData) child;
		        return cd.getData();
		    }
		    return "";
		}
	}

	public void getTempC() {
		//This function will define rate(max is 2.5) and desciption text from temperature.
		double min = 20;
		double max = 30;
		if (temp >= min && temp <= max) {
			tempRate = 2.5;
			tempTxt = "";
		} else if (temp > max && temp <= max + 5) {
			tempRate = 1.5;
			tempTxt = "A little bit hot";
		} else if (temp > max + 5 && temp <= max + 10) {
			tempRate = 0.5;
			tempTxt = "Very hot";
		} else if (temp > max + 10) {
			tempRate = 0;
			tempTxt = "Too hot";
		} else if (temp < min && temp >= min - 5) {
			tempRate = 1.5;
			tempTxt = "A little bit cold";
		} else if (temp < min - 5 && temp >= min - 10) {
			tempRate = 0.5;
			tempTxt = "Very cold";
		} else if (temp < min - 10) {
			tempRate = 0;
			tempTxt = "Too cold";
		} else {
			tempRate = 0;
			tempTxt = "Cannot measure temperature";
		}
	}

	public void getLux() {
		//This function will define rate(max is 2.5) and desciption text from light sensor value.
		double min = 300;
		double max = 750;
		if (lux >= min && lux <= max) {
			luxRate = 2.5;
			luxTxt = "";
		} else if (lux < min - 100 && lux >= min - 100) {
			luxRate = 1.5;
			luxTxt = "A little bit dark";
		} else if (lux < min - 100) {
			luxRate = 0;
			luxTxt = "Too dark";
		} else if (lux > max && lux <= max + 100) {
			luxRate = 1.5;
			luxTxt = "A little bit bright";
		} else if (lux > max + 100) {
			luxRate = 0;
			luxTxt = "Too bright";
		} else {
			luxRate = 0;
			luxTxt = "Cannot measure brightness";
		}
	}

	public void getRate() {
		//This function will set rate of RatingBar(Star) and set text show in activity UI
		getTempC();
		getLux();
		rate = tempRate + luxRate;
		ratingBar.setRating((float) rate);
		txtResult = "\nTemperature : " + temp + " °C " + tempTxt
				+ "\nBrightness : " + lux + " LUX " + luxTxt;
		textResult.setText(txtResult);
	}

	

}